
import { getUserInfo } from '@/api/login'
import { getCookieByKey, setCookie, clearAllCookies } from '@/utils/auth'
import { resetRouter } from '@/router'
import { COOKIE_PREFIX, TOKEN } from '@/api/constant'

const state = {
  token : getCookieByKey( TOKEN ),
  nickName : '',
  id : '',
  roles : []
}

const mutations = {
  SET_TOKEN : ( state, token ) => {
    state.token = token || ''
  },
  SET_USER_INFOS( state, data ) {
    state.nickName = data.name || ''
    state.id = data.id || ''
    state.roles = data.roles
  },
  CLEAR_USER_INFOS( state ) {
    state.nickName = ''
    state.token = ''
    state.id = ''
    state.roles = []
  }
}

const actions = {
  saveToken( { commit }, token ) {
    commit( 'SET_TOKEN', token )
    setCookie( TOKEN, token )
  },
  // token 登录 TODO
  getUserInfo( { commit, state }, payload ) {
    return new Promise( ( resolve, reject ) => {
      const response = {
        code : 200,
        message : "success",
        data : {
          id : 9527,
          nickName : '编号9527',
          token : 'token9527'
        }
      }
      const { data } = response
      data.roles = ['admin']
      for ( const key in data ) {
        setCookie( `${COOKIE_PREFIX}${key}`, data[key] )
      }
      commit( 'SET_USER_INFOS', data )
      resolve( data )



      // getUserInfo()
      //   .then( response => {
      //     const { data, code } = response
      //     if ( !data || code != 200 ) {
      //       reject( 'token登录失败' )
      //     }
      //     data.roles = data.permission == 1 ? ['admin'] : ['user']
      //     data.token = payload.token || state.token
      //     commit( 'SET_USER_INFOS', data )
      //
      //     for ( const key in data ) {
      //       setCookie( `${COOKIE_PREFIX}${key}`, data[key] )
      //     }
      //     resolve( data )
      //   } )
      //   .catch( error => {
      //     reject( error )
      //     commit( 'CLEAR_USER_INFOS' )
      //     clearAllCookies()
      //     resetRouter()
      //   } )
    } )
  },
  // 退出 TODO
  LoginOut( { dispatch } ) {
    return new Promise( ( resolve, reject ) => {
      dispatch( 'user/resetInfo', null, { root : true } )
      resolve()
    } )
  },
  // 清空所有登录信息
  resetInfo( { commit, dispatch } ) {
    return new Promise( ( resolve, reject ) => {
      commit( 'CLEAR_USER_INFOS' )
      clearAllCookies()
      resetRouter()
      dispatch( 'tagsView/delAllViews', null, { root : true } )
      resolve()
    } )
  }
}

export default {
  namespaced : true,
  state,
  mutations,
  actions
}
